//The MIT License (MIT)
//
//Copyright (c) 2014 Adam Paszke
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.

let net = require('react-native-tcp');
let performance = global.performance || {};
let performanceNow =
  performance.now ||
  performance.mozNow ||
  performance.msNow ||
  performance.oNow ||
  performance.webkitNow ||
  function () {
    return new Date().getTime();
  };
function hrtime(previousTimestamp) {
  let clocktime = performanceNow.call(performance) * 1e-3;
  let seconds = Math.floor(clocktime);
  let nanoseconds = Math.floor((clocktime % 1) * 1e9);
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0];
    nanoseconds = nanoseconds - previousTimestamp[1];
    if (nanoseconds < 0) {
      seconds--;
      nanoseconds += 1e9;
    }
  }
  return [seconds, nanoseconds];
}

export const ping = function (options, callback) {
  let i = 0;
  let results = [];
  options.address = options.address || 'localhost';
  options.port = options.port || 80;
  options.attempts = options.attempts || 10;
  options.timeout = options.timeout || 5000;
  let check = function (options, callback) {
    if (i < options.attempts) {
      connect(options, callback);
    } else {
      let avg = results.reduce(function (prev, curr) {
        return prev + curr.time;
      }, 0);
      let max = results.reduce(function (prev, curr) {
        return prev > curr.time ? prev : curr.time;
      }, results[0].time);
      let min = results.reduce(function (prev, curr) {
        return prev < curr.time ? prev : curr.time;
      }, results[0].time);
      avg = avg / results.length;
      let out = {
        address: options.address,
        port: options.port,
        attempts: options.attempts,
        avg: avg,
        max: max,
        min: min,
        results: results,
      };
      callback(undefined, out);
    }
  };

  let connect = function (options, callback) {
    let s = new net.Socket();
    //console.log('global.process', global.process);
    let start = hrtime();
    //console.log(start);
    s.connect(options.port, options.address, function () {
      let time_arr = hrtime(start);
      let time = (time_arr[0] * 1e9 + time_arr[1]) / 1e6;
      results.push({seq: i, time: time});
      s.destroy();
      i++;
      check(options, callback);
    });
    s.on('error', function (e) {
      results.push({seq: i, time: undefined, err: e});
      s.destroy();
      i++;
      check(options, callback);
    });
    s.setTimeout(options.timeout, function () {
      results.push({seq: i, time: undefined, err: Error('Request timeout')});
      s.destroy();
      i++;
      check(options, callback);
    });
  };
  connect(options, callback);
};
export const probe = function (address, port, callback) {
  address = address || 'localhost';
  port = port || 80;
  ping(
    {address: address, port: port, attempts: 1, timeout: 5000},
    function (err, data) {
      let available = data.min !== undefined;
      callback(err, available);
    },
  );
};
export const ping_async = function (options) {
  return new Promise((resolve, reject) => {
    ping(options, function (err, data) {
      if (err) {
        reject(err);
      }
      if (data) {
        resolve(data);
      }
    });
  });
};
export const probe_async = function (address, port) {
  return new Promise((resolve, reject) => {
    probe(address, port, function (err, data) {
      if (err) {
        console.log(err);
        reject(err);
      }
      if (data) {
        console.log(data);
        resolve(data);
      }
    });
  });
};
// ping({
//   address:`123.58.210.13`,
//   port:8546,
//   attempts:1,
//   timeout:3000
// },function (err,data) {
//   console.log(`ping----`,data,err);
// })
